package com.chris.fibonacci_sequence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private LinearLayout llFibonacci;
    private EditText etIndexFib;
    private Button button;
    private TextView tvFibonacciNumList;
    private TextView tvNthFibonacciNumber;
    private GifView gifView;

    int index;
    private ProgressDialog progressDialog;
    //线程处理 Handler Thread
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what){
                case 1:
                    try {
                        showFibonacciSequence(index,tvFibonacciNumList);//show the whole Fibonacci Sequence,just like 1,1,2,3...
                    }catch (Exception e){
                        Toast.makeText(getApplicationContext(),getResources().getString(R.string.exception_toast),Toast.LENGTH_SHORT).show();
                    }finally {
                        progressDialog.dismiss();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();//隐藏标签栏
        initViews();
    }

    private void initViews() {
        progressDialog = ProgressDialog.show(this,"Toast","loading");
        progressDialog.dismiss();
        llFibonacci = findViewById(R.id.ll_fibonacci);
        etIndexFib = findViewById(R.id.et_index_fib);
        button = findViewById(R.id.button);
        tvFibonacciNumList = findViewById(R.id.tv_fibonacci_num_list);
        tvNthFibonacciNumber = findViewById(R.id.tv_nth_fibonacci_number);
        gifView = findViewById(R.id.gifView);
        //load gif
        gifView.setGifResource(R.raw.fibonacci);
        progressDialog.setMessage("loading");
        tvFibonacciNumList.setSelected(true);
        //set button Listener
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!TextUtils.isEmpty(etIndexFib.getText().toString())){
                    index = Integer.parseInt(etIndexFib.getText().toString());
                    progressDialog.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    }).start();
                }else{
                    Toast.makeText(getApplicationContext(),getResources().getString(R.string.toast),Toast.LENGTH_SHORT).show();
                }
            }
        });
        //set editText listener
        etIndexFib.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               if(charSequence.length() == 0) {
                   tvFibonacciNumList.setText(getResources().getText(R.string.list));
                   tvNthFibonacciNumber.setText(getResources().getText(R.string.result));
               }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void showFibonacciSequence(int index, TextView tvFibonacciNumList) {
        ArrayList fibonacci_sequence_list = new ArrayList<Long>();
        StringBuilder stringBuilder = new StringBuilder();
        if(index < 0){
            throw new IllegalArgumentException("it doesn't exist！");
        }

        for(int i=0; i <= index; i++) {
            long fibonacci_num = createFibonacciSequence(i);
            fibonacci_sequence_list.add(fibonacci_sequence_list);
            stringBuilder.append(fibonacci_num);
            if(i < index){
                stringBuilder.append(",");
            }
            if(i == index){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvNthFibonacciNumber.setText(String.valueOf(fibonacci_num));
                    }
                });
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvFibonacciNumList.setText(stringBuilder.toString());
            }
        });
    }

    /**
     * 斐波那契数列 Fibonacci sequence create function
     *     using long replaced of int
     *     for the long has bigger data storage
     * @param index  the nth Fibonacci number
     */

    public static long createFibonacciSequence(int index){
        if(index < 0)
            throw new IllegalArgumentException("it doesn't exist！");
        if(index == 0){
            return 1L;
        }
        if( index == 1){
            return 1L;
        }else{
            return (createFibonacciSequence(index-1) + createFibonacciSequence( index-2));
        }
    }


}